export class BasicCalculator {
  constructor(root) {
    this.root = root;
    this.render();
  }
  render() {
    this.root.innerHTML = `
      <div class="display" id="basicDisplay">0</div>
      <div class="grid cols-4">
        <button class="key" data-k="C">C</button>
        <button class="key" data-k="BS">⌫</button>
        <button class="key" data-k="%">%</button>
        <button class="key" data-k="/">÷</button>
        <button class="key" data-k="7">7</button>
        <button class="key" data-k="8">8</button>
        <button class="key" data-k="9">9</button>
        <button class="key" data-k="*">×</button>
        <button class="key" data-k="4">4</button>
        <button class="key" data-k="5">5</button>
        <button class="key" data-k="6">6</button>
        <button class="key" data-k="-">−</button>
        <button class="key" data-k="1">1</button>
        <button class="key" data-k="2">2</button>
        <button class="key" data-k="3">3</button>
        <button class="key" data-k="+">+</button>
        <button class="key" data-k="0" style="grid-column: span 2">0</button>
        <button class="key" data-k=".">.</button>
        <button class="key primary" data-k="=">=</button>
      </div>
    `;
    this.display = this.root.querySelector("#basicDisplay");
    this.expr = "";
    this.root
      .querySelectorAll(".key")
      .forEach((btn) =>
        btn.addEventListener("click", () => this.onKey(btn.dataset.k))
      );
  }
  onKey(k) {
    if (k === "C") {
      this.expr = "";
      this.update();
      return;
    }
    if (k === "BS") {
      this.expr = this.expr.slice(0, -1);
      this.update();
      return;
    }
    if (k === "=") {
      this.evaluate();
      return;
    }
    this.expr += k;
    this.update();
  }
  update() {
    this.display.textContent = this.expr || "0";
  }
  evaluate() {
    try {
      const sanitized = this.expr.replace(/÷/g, "/").replace(/×/g, "*");
      const value = Function(`"use strict"; return (${sanitized})`)();
      this.expr = String(value);
      this.update();
    } catch (_e) {
      this.display.textContent = "Error";
    }
  }
}
